package ejb.dao;

import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import ejb.entity.City;

@Stateless
public class DefaultCityDAO implements CityDAO {
	
	@PersistenceContext
	private EntityManager em;

	@SuppressWarnings("unchecked")
	@Override
	public List<City> getCities() {
		List<City> cities = em.createNamedQuery("DefaultCity.findAll").getResultList();
		return cities;
	}
	
	public City getById(int id) {
		try{
			return (City)em.createNamedQuery("DefaultCity.findById").setParameter("id", id).getSingleResult();
		}catch(NoResultException nre){
			return null;
		}catch(IllegalArgumentException e){
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<City> getDetachedCities(){
		List<City> cities = em.createNamedQuery("DefaultCity.findAll").getResultList();
		Iterator<City> it = cities.iterator();
		while(it.hasNext()){
			City city= it.next();
			em.detach(city);
		}
		return cities;		
	}
}
